package com.ruoyi.base.service.impl;

import java.math.BigDecimal;
import java.util.*;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.base.domain.vo.LotteryItemVo;
import com.ruoyi.base.domain.vo.LotteryVo;
import com.ruoyi.brand.*;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.sale.domain.*;
import com.ruoyi.sale.service.*;
import com.ruoyi.utils.LotteryUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.base.mapper.BaseLotteryMapper;
import com.ruoyi.base.domain.BaseLottery;
import com.ruoyi.base.service.IBaseLotteryService;

/**
 * 彩票基础数据Service业务层处理
 *
 * @author szm
 * @date 2025-09-23
 */
@Slf4j
@Service
public class BaseLotteryServiceImpl extends ServiceImpl<BaseLotteryMapper, BaseLottery> implements IBaseLotteryService {
    @Autowired
    private ISaleLotteryOneService oneService;

    @Autowired
    private ISaleLotterySixService sixService;

    @Autowired
    private ISaleLotteryThreeService threeService;

    @Autowired
    private ISaleConfigStyleService configStyleService;

    @Autowired
    private ISaleRevenueService revenueService;

    @Autowired
    private RedisCache redisCache;

    @Override
    public void syncLottery() {

        baseMapper.deleteAll();
        oneService.deleteAll();
        threeService.deleteAll();
        sixService.deleteAll();

        List<BaseLottery> lotteries = new ArrayList<>();

        List<String> oneList = LotteryUtil.botteryOne();
        for (String str : oneList) {
            BaseLottery lottery = new BaseLottery();
            lottery.setLotteryNo(str);
            lottery.setLotteryDate(new Date());
            lottery.setLotteryType(1);
            lottery.setLotteryName("直选");
            lottery.setStatusType(1);
            lottery.setStatusName("正常");
            lottery.setBuyNo(BigDecimal.ZERO);
            lottery.setMaxBuyNo(0);
            lottery.setCreateTime(new Date());
            lottery.setUpdateTime(new Date());
            lottery.setCreateBy("admin");
            lottery.setUpdateBy("admin");
            lotteries.add(lottery);
        }


        // 组三复式
        List<String> threeList = LotteryUtil.botteryThree();
        for (String str : threeList) {
            BaseLottery lottery = new BaseLottery();
            lottery.setLotteryNo(str);
            lottery.setLotteryDate(new Date());
            lottery.setLotteryType(2);
            lottery.setLotteryName("组三");
            lottery.setStatusType(1);
            lottery.setStatusName("正常");
            lottery.setBuyNo(BigDecimal.ZERO);
            lottery.setMaxBuyNo(0);
            lottery.setCreateTime(new Date());
            lottery.setUpdateTime(new Date());
            lottery.setCreateBy("admin");
            lottery.setUpdateBy("admin");
            lotteries.add(lottery);
        }


        //组六复式
        List<String> sixList = LotteryUtil.botterySix();
        for (String str : sixList) {
            BaseLottery lottery = new BaseLottery();
            lottery.setLotteryNo(str);
            lottery.setLotteryDate(new Date());
            lottery.setLotteryType(3);
            lottery.setLotteryName("组六");
            lottery.setStatusType(1);
            lottery.setStatusName("正常");
            lottery.setBuyNo(BigDecimal.ZERO);
            lottery.setMaxBuyNo(0);
            lottery.setCreateTime(new Date());
            lottery.setUpdateTime(new Date());
            lottery.setCreateBy("admin");
            lottery.setUpdateBy("admin");
            lotteries.add(lottery);
        }

        baseMapper.insert(lotteries);
    }

    @Override
    public List<LotteryVo> buyLotter(LotteryVo lotter) {
        List<LotteryVo> b = new ArrayList<>();
        if (lotter.getLotteryType() == 1) {
            delRedis();
            b = oneService.buyNumLottery(lotter);

            BigDecimal buyGroup = lotter.getBuyGroup();
            if (buyGroup.compareTo(BigDecimal.ZERO) > 0) {
                String[] strs = lotter.getLotteryNo().split(",");
                Map<String, Long> longMapThree = LotteryUtil.isAABPatternThree(strs);
                if (CollectionUtil.isNotEmpty(longMapThree)) {
                    List<LotteryVo> voList = threeService.buyOneNumLottery(longMapThree, lotter);
                    b.addAll(voList);
                }

                Map<String, Long> longMapSix = LotteryUtil.isAABPatternSix(strs);
                if (CollectionUtil.isNotEmpty(longMapSix)) {
                    List<LotteryVo> voList = sixService.buyOneNumLottery(longMapSix, lotter);
                    b.addAll(voList);
                }

            }

            if (updateRedis()) {
                this.delRedis();
            }

        } else if (lotter.getLotteryType() == 2) {
            String lotters = lotter.getLotteryNo();
            Map<String, Set<String>> map = new TreeMap<>();
            String[] split = lotters.split(",");
            for (String str : split) {
                Set<String> sets = LotteryUtil.threeCombinations(str);
                map.put(str, sets);
            }
            lotter.setSetMap(map);
            b = threeService.buyNumLottery(lotter);
        } else if (lotter.getLotteryType() == 3) {
            String lotters = lotter.getLotteryNo();
            Map<String, Set<String>> map = new TreeMap<>();
            String[] split = lotters.split(",");
            for (String str : split) {
                Set<String> sets = LotteryUtil.sixCombinations(str);
                map.put(str, sets);
                //lotter.setLotteryNo(sets.stream().collect(Collectors.joining(",")));
                //set.addAll(strings);
            }
            lotter.setSetMap(map);
            b = sixService.buyNumLottery(lotter);

        } else if (lotter.getLotteryType() == 4) {
            String lotters = lotter.getLotteryNo();
            Map<String, Set<String>> map = new TreeMap<>();
            String[] split = lotters.split(",");
            for (String str : split) {
                Set<String> sets = LotteryUtil.oneCombinations(str);
                map.put(str, sets);
            }
            lotter.setSetMap(map);
            b = oneService.buyNumLotterySet(lotter);
        }

        return b;
    }

    @Override
    public String buyLotter2(LotteryVo lotter) {

        log.info("接受的数据："+JSON.toJSONString(lotter));
        String path = "";
        LotteryVo lotteryNew = new LotteryVo();
        BeanUtils.copyProperties(lotter, lotteryNew);

        List<LotteryVo> b = new ArrayList<>();
        b.add(lotter);
        if (lotter.getLotteryType() == 1) {
            redisCache.deleteObject("lotter_1");
            redisCache.setCacheObject("lotter_1",lotter);

            List<LotteryItemVo> oneList = new ArrayList<>();
            List<LotteryItemVo> threeList = new ArrayList<>();
            List<LotteryItemVo> sixList = new ArrayList<>();

            List<LotteryItemVo> itemList = lotter.getItemList();
            for (LotteryItemVo item : itemList) {
                if (item.getItemType().contains("组")) {
                    char[] str = item.getItemVal().toCharArray();
                    Arrays.sort(str);
                    String sort = new String(str);
                    item.setItemVal(sort);

                    if (str[0] < str[1] && str[1] < str[2]) {
                        item.setItemType("组六");
                        sixList.add(item);
                    } else {
                        item.setItemType("组三");
                        threeList.add(item);
                    }
                } else {
                    item.setItemType("单选");
                    oneList.add(item);
                }
            }
            if (oneList.size() > 0) {
                lotteryNew.setItemList(oneList);
                oneService.buyNum3DSingle(lotteryNew);
            }

            if (threeList.size() > 0) {
                lotteryNew.setItemList(threeList);
                threeService.buyNum3DSingle(lotteryNew);
            }

            if (sixList.size() > 0) {
                lotteryNew.setItemList(sixList);
                sixService.buyNum3DSingle(lotteryNew);
            }
            if (updateRedis()) {
                this.delRedis();
                path = getGeentPdf(lotter);
            }
        } else if(lotter.getLotteryType() == 2){
            String lotters = lotter.getLotteryNo();
            Map<String, Set<String>> map = new TreeMap<>();
            Set<String> sets = LotteryUtil.threeCombinations(lotters);
            map.put(lotters, sets);
            /*String[] split = lotters.split(",");
            for (String str : split) {
                Set<String> sets = LotteryUtil.threeCombinations(str);
                map.put(str, sets);
            }*/
            lotter.setSetMap(map);
            lotter.setNumbers(sets.size());
            b = threeService.buyNumLottery(lotter);
            if (b.size() > 0){
                lotter.setRemark("组三复式投注");
                path = getGeentPdf(lotter);
            }
        } else if(lotter.getLotteryType() == 3){
            String lotters = lotter.getLotteryNo();
            Map<String, Set<String>> map = new TreeMap<>();
            Set<String> sets = LotteryUtil.sixCombinations(lotters);
            map.put(lotters, sets);
            /*String[] split = lotters.split(",");
            for (String str : split) {
                Set<String> sets = LotteryUtil.sixCombinations(str);
                map.put(str, sets);
            }*/
            lotter.setSetMap(map);
            lotter.setNumbers(sets.size());
            b = sixService.buyNumLottery(lotter);
            if (b.size() > 0){
                lotter.setRemark("组六复式投注");
                path = getGeentPdf(lotter);
            }
        } else if(lotter.getLotteryType() == 4){
            String lotters = lotter.getLotteryNo();
            Map<String, Set<String>> map = new TreeMap<>();
            Set<String> sets = LotteryUtil.oneCombinations(lotters);
            map.put(lotters, sets);
            /*String[] split = lotters.split(",");
            for (String str : split) {
                Set<String> sets = LotteryUtil.oneCombinations(str);
                map.put(str, sets);
            }*/
            lotter.setSetMap(map);
            lotter.setNumbers(sets.size());
            b = oneService.buyNumLotterySet(lotter);
            if (b.size() > 0){
                lotter.setRemark("单选单复式投注");
                path = getGeentPdf(lotter);
            }
        }
        return path;
    }

    @Override
    public int updateBuyNo(BigDecimal buyNo, String lotteryNo, Integer lotteryType) {
        return baseMapper.updateBuyNo(buyNo, lotteryNo, lotteryType);

    }

    @Override
    public BaseLottery isMaxBuyNo(BigDecimal buyNo, String lotteryNo, Integer lotteryType) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("lottery_no", lotteryNo);
        wrapper.eq("lottery_type", lotteryType);
        BaseLottery lottery = baseMapper.selectOne(wrapper);

        BigDecimal multiply = lottery.getBuyNo().add(buyNo);
        if (multiply.compareTo(new BigDecimal(lottery.getMaxBuyNo())) <= 0) {
            lottery.setStatus(1);
            lottery.setBuyNo(multiply);
            return lottery;
        } else {
            lottery.setStatus(2);
            return lottery;
        }
    }

    @Override
    public int updateAll(Integer maxBuyNo, String lotteryType) {
        return baseMapper.updateAll(maxBuyNo, lotteryType);
    }

    @Override
    public void delRedis() {
        redisCache.deleteObject("oneUpBuy");
        redisCache.deleteObject("oneData");
        redisCache.deleteObject("threeUpBuy");
        redisCache.deleteObject("threeData");
        redisCache.deleteObject("sixUpBuy");
        redisCache.deleteObject("sixData");
    }

    @Override
    public LotteryVo getLastLotter() {
        LotteryVo lotteryVo = redisCache.getCacheObject("lotter_1");
        return lotteryVo;
    }

    public boolean updateRedis() {
        try {
            if (redisCache.hasKey("oneUpBuy")) {
                List<BaseLottery> oneUpBuy = redisCache.getCacheList("oneUpBuy");
                this.updateBatchById(oneUpBuy);

                List<SaleLotteryOne> oneData = redisCache.getCacheList("oneData");
                oneService.saveBatch(oneData);

            }
            if (redisCache.hasKey("threeUpBuy")) {
                List<BaseLottery> threeUpBuy = redisCache.getCacheList("threeUpBuy");
                this.updateBatchById(threeUpBuy);

                List<SaleLotteryThree> threeData = redisCache.getCacheList("threeData");
                threeService.saveBatch(threeData);

            }

            if (redisCache.hasKey("sixUpBuy")) {

                List<BaseLottery> sixUpBuy = redisCache.getCacheList("sixUpBuy");
                this.updateBatchById(sixUpBuy);

                List<SaleLotterySix> sixData = redisCache.getCacheList("sixData");
                sixService.saveBatch(sixData);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public String getGeentPdf(LotteryVo lotter){

        Long deptId = SecurityUtils.getLoginUser().getDeptId();
        SysDept dept = SecurityUtils.getLoginUser().getUser().getDept();
        SaleConfigStyle configStyle = configStyleService.getByDeptId(deptId);

        if (StringUtils.isEmpty(lotter.getSheng())){
            lotter.setSheng("shanxian");
        }

        Map<String,String> map = new HashMap<>();
        if (lotter.getSheng().equals("shangdong")){
            if(lotter.getLotteryType() == 1){
                map =  ShanDong3DdanShi.generateLotteryTicket(lotter);
            }else{
                map =  ShanDong3DFushi.generateLotteryTicket(lotter);
            }

        }
        if (lotter.getSheng().equals("shanxian")){
            if(lotter.getLotteryType() == 1){
                map =  ShanXian3DdanShi.generateLotteryTicket(lotter,configStyle);
            }else{
                map =  ShanXian3DFushi.generateLotteryTicket(lotter,configStyle);
            }

        }

        if (!lotter.getBuyName().contains("测试")){
            if (map.get("status").equals("yes")){
                String money = map.get("money");
                SaleRevenue revenue = new SaleRevenue();
                revenue.setApplyDate(new Date());
                revenue.setDeptId(deptId+"");
                revenue.setDeptName(dept.getDeptName());
                revenue.setMoney(Integer.valueOf(money));
                revenue.setCreateTime(new Date());
                revenue.setUpdateTime(new Date());
                revenueService.save(revenue);
            }
        }
        return map.get("path");
    }

}
